iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 13
0
Modern Web

Angular - 從零開始系列 第 13

Angular - 從零開始 - Day13 - 結構型指令 ngIf

  • 分享至 

  • xImage
  •  

angular

會透過指令來新增或刪除 DOM 元素和改變 DOM 結構,例如 ngIfngForngSwitch 皆可控制 DOM 結構。

  • ngSwitch 前面不要* 星號。
  • ngIfngForngSwitchDefault 以及 ngSwitchCase 前面加上 * 星號。

ngIf

目前有六個圓形,編號為 1~6,透過 ngIf 指令,要完成以下事情,

  1. 擊次數為基數時,留下 1~3 的圓形。
  2. 點擊次數為偶數時,留下 4~6 圓形。

首先建立 html 所需要的內容。

app.component.html

<h2>ngIf</h2>
<button>click</button>
<ul>
  <li><a class="circle red" href="#">1</a></li>
  <li><a class="circle orange" href="#">2</a></li>
  <li><a class="circle yellow" href="#">3</a></li>
</ul>
<ul>
  <li><a class="circle green" href="#">4</a></li>
  <li><a class="circle blue" href="#">5</a></li>
  <li><a class="circle purple" href="#">6</a></li>
</ul>

加入 ngIf

因為是基偶數更換時,要更換一組 ul,所以 ngIf 要寫在 ul 標籤上,就會變成下方程式碼,並且帶入上一篇寫過的 addCounter() 的方法。。

<h2>ngIf</h2>
<button (click)="addCounter()">click</button>
<ul *ngIf="counter % 2 == 0">
  <li><a class="circle red" href="#">1</a></li>
  <li><a class="circle orange" href="#">2</a></li>
  <li><a class="circle yellow" href="#">3</a></li>
</ul>
<ul *ngIf="counter % 2 == 1">
  <li><a class="circle green" href="#">4</a></li>
  <li><a class="circle blue" href="#">5</a></li>
  <li><a class="circle purple" href="#">6</a></li>
</ul>

app.component.ts

export class AppComponent {
  counter = 0;
  constructor() {}
  addCounter() {
    this.counter++;
  }
}

app.component.css
不在本次陳述重點,又因為有點長,故不贅述。

注意事項

ngIf 是會移除整個 template 的內容,並不是單純隱藏,所以包含在 ngIf 中的 template,會因為此指令關係整個都會被移除或新增回來,在使用上要注意此規則。

Demo

https://stackblitz.com/edit/angular-ivy-hhxay5?file=src/app/app.component.html


上一篇
Angular - 從零開始 - Day12 - 屬性型指令
下一篇
Angular - 從零開始 - Day14 - 結構型指令 ngSwitch
系列文
Angular - 從零開始25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言